617. 合并二叉树
为保证权益,题目请参考 617. 合并二叉树(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2)
{
TreeNode *root;
mergeTreesHelper(root, t1, t2);
}
void mergeTreesHelper(TreeNode *root, TreeNode *left, TreeNode *right)
{
if (left == NULL)
{
if (right == NULL)
{
root = NULL;
}
else
{
root = new TreeNode(right->val);
mergeTreesHelper(root->left, NULL, right->left);
mergeTreesHelper(root->right, NULL, right->right);
}
}
else
{
if (right == NULL)
{
root = new TreeNode(left->val);
mergeTreesHelper(root->left, left->left, NULL);
mergeTreesHelper(root->right, left->right, NULL);
}
else
{
root = new TreeNode(left->val + right->val);
mergeTreesHelper(root->left, left->left, right->left);
mergeTreesHelper(root->right, left->right, left->left);
}
}
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57